package com.jwater.core.net;

import java.util.List;

import jwater.io.netty.buffer.ByteBuf;
import jwater.io.netty.channel.ChannelHandlerContext;
import jwater.io.netty.handler.codec.MessageToMessageDecoder;
/**
 * @description:
 * @author: jnner
 * @createDate: 2021/2/5
 * @version: 1.0
 */
public class NettyDecoder extends MessageToMessageDecoder<ByteBuf> {

	@Override
	protected void decode(ChannelHandlerContext context, ByteBuf buf, List<Object> list) throws Exception {
		while (buf.readableBytes() >= 14) {
			NodePacket packet = new NodePacket();
			// 标记位置
			buf.markReaderIndex();
			packet.setVersion(buf.readShort());
			packet.setDataType(buf.readInt());
			packet.setNumber(buf.readInt());
			packet.setLength(buf.readInt());
			if (packet.getLength() == 0) {
				list.add(packet);
				continue;
			} else {
				if (buf.readableBytes() >= packet.getLength()) {
					byte[] data = new byte[packet.getLength()];
					buf.readBytes(data);
					packet.setData(data);
					list.add(packet);
				} else {
					// 回到标记位置
					buf.resetReaderIndex();
				}
			}
		}
	}

}
